package cn.szq.concurrent.thread.completableFuture;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.stream.IntStream;

/**
 * @ClassName: SemaphoreDemo
 * @Description:
 * @Author: szq
 * @Date: 2021-10-22 09:21:40
 */
public class SemaphoreDemo {

    static Semaphore semaphore = new Semaphore(10);

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(50);
        IntStream.rangeClosed(1, 500).forEach(t-> executorService.submit(new Task()));
        executorService.shutdown();
    }

    static class Task implements Runnable{

        @Override
        public void run() {
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "拿到了许可证，花费2秒执行慢查询。");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("慢查询执行完成，" + Thread.currentThread().getName() + "释放了许可证。");
            semaphore.release();
        }
    }

}
